package com.guli.gulimall.gulimallproduct.service.impl;

import com.guli.common.utils.ProductConstant;
import com.guli.common.utils.R;
import com.guli.gulimall.gulimallproduct.entity.*;
import com.guli.gulimall.gulimallproduct.feign.CouponFeignService;
import com.guli.gulimall.gulimallproduct.feign.ElassticFeignService;
import com.guli.gulimall.gulimallproduct.feign.WareFeignService;
import com.guli.gulimall.gulimallproduct.service.*;
import com.guli.gulimall.gulimallproduct.vo.spuvo.*;
import com.guli.to.SkuHasStockVo;
import com.guli.to.SkureductionTo;
import com.guli.to.SpuBoundsTo;
import com.guli.to.es.SkuEsModel;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.gulimallproduct.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.templateresolver.FileTemplateResolver;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuInfoService spuInfoService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueServiceImpl productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private ElassticFeignService elassticFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //    由于保存的东西过多，需要加上事务注解，有异常的时候回滚，无异常就正常提交
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo skuInfoVo) {
        //1、保存spu基本信息 pms_spu_info
        //2 保存spu的描述图片 pms_spu_info_desc
        // 3保存spu的图片集 pms_spu_images
        //4 保存spu的规格参数 商品属性 pms_product_attr_vallue
        /**
         *  保存spu的积分信息：sms->spu_bounds
         */
        //5保存当前spu对应的sku信息
        /**
         * 5.1  sku的基本信息 pms_sku_info
         * 5.2 sku的图片信息 pms_sku_images
         * 5.3 sku的销售信息  pms_sku_sale_attr_value
         * 5.4 sku的优惠、满减等信息sms->sku_laddder/sku_full_reduction/memer_price/s
         */

        //开始实现
        //1保存spu的基本信息
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(skuInfoVo, spuInfoEntity);
        spuInfoEntity.setCatalogId(skuInfoVo.getCatalogId());

        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //2 保存spu的描述图片 pms_spu_info_desc
        List<String> descript = skuInfoVo.getRealdecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", descript));
        this.saveSpuInfoDesc(spuInfoDescEntity);
        //3保存spu的图片集 pms_spu_images
        List<String> realimagesurl = skuInfoVo.getRealimagesurl();
        this.spuImagesService.saveImages(spuInfoEntity.getId(), realimagesurl);
        //4 保存spu的规格参数 商品属性 pms_product_attr_vallue
        List<Attr> baseAttrs = skuInfoVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());
            String name = attrService.getById(attr.getAttrId()).getAttrName();
            productAttrValueEntity.setAttrName(name);
            productAttrValueEntity.setAttrValue(attr.getAttrValue());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(productAttrValueEntityList);
        // sku的基本信息 pms_sku_info
        List<Skus> skus = skuInfoVo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultimg = "";
                for (Images images : item.getImages()) {
                    if (images.getDefaultImg() == 1) {
                        defaultimg = images.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount((long) 0);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(skuInfoVo.getCatalogId());
                skuInfoEntity.setSkuDefaultImg(defaultimg.split("=")[1]);

                // skuInfoEntity.setCatalogId(skuInfoVo.getCatalogId());
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    System.out.println(img);
                    if (img.getDefaultImg() == 1) skuImagesEntity.setImgUrl(img.getImgUrl().split("=")[1]);
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                //5.2 sku的图片信息 pms_sku_images
                skuImagesService.saveBatch(imagesEntities);
                //5.3 sku的销售信息  pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5.4 sku的优惠、满减等信息sms->sku_laddder/sku_full_reduction/memer_price
                SkureductionTo skureductionTo = new SkureductionTo();
                BeanUtils.copyProperties(item, skureductionTo);
                skureductionTo.setSkuId(skuId);
                //skureductionTo.setMemberPrice(item.getMemberPrice());
                if (skureductionTo.getFullCount() > 0 || skureductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponService.saveSkuReduction(skureductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保优惠信息失败");
                    }
                }

            });
        }
        //保存spu的积分信息：sms->spu_bounds
        Bounds bounds = skuInfoVo.getBounds();
        SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
        BeanUtils.copyProperties(bounds, spuBoundsTo);
        spuBoundsTo.setSpuId(spuInfoEntity.getId());
        R r = couponService.saveSpuBounds(spuBoundsTo);
        if (r.getCode() != 0) {
            log.error("远程保存积分信息失败");
        }
    }

    @Transactional
    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        this.spuInfoDescService.saveOrUpdate(spuInfoDescEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        //status: 1
        //key: ee
        //brandId: 20
        //catelogId: 684

        String key = (String) params.get("key");
        if (null != key && !key.isEmpty() && !"0".equalsIgnoreCase(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String status = (String) params.get("status");
        if (null != status && !status.isEmpty()) {
            wrapper.and(w -> {
                w.eq("publish_status", status);
            });
        }
        String brandId = (String) params.get("brandId");
        if (null != brandId && !brandId.isEmpty() && !"0".equalsIgnoreCase(brandId)) {
            wrapper.and(w -> {
                w.eq("brand_id", brandId);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (null != catelogId && !catelogId.isEmpty() && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.and(w -> {
                w.eq("catalog_id", catelogId);
            });
        }
        System.out.println(key + "," + status + "," + brandId + "," + catelogId);
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    /**
     * 商品上架
     *
     * @param spuId
     */
    @Override
    public R productUp(Long spuId) {
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.listforspuByspuId(String.valueOf(spuId));
        List<Long> attrids = productAttrValueEntities.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
        List<Long> selectSearchAttrsIds = attrService.selectSearchAttrs(attrids);
        Set<Long> Idset = new HashSet<>(selectSearchAttrsIds);
        List<SkuEsModel.Attrs> attrs = new ArrayList<>();
        attrs = productAttrValueEntities.stream().filter(item -> {
            return Idset.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            attrs1.setAttrId(item.getAttrId());
            attrs1.setAttrName(item.getAttrName());
            attrs1.setAttrValue(item.getAttrValue());
            return attrs1;
        }).collect(Collectors.toList());
        System.out.println("商品属性");
        System.out.println(attrs);
        //1查出当前spuid所对应的sku信息,品牌名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);
        System.out.println("商品sku属性");
        System.out.println(skuInfoEntities);
        Map<Long, Boolean> stomap = null;
        //查询库存
        try {
            List<Long> skuList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).filter(Objects::nonNull).collect(Collectors.toList());
            List<SkuHasStockVo> HasStocks = wareFeignService.hashStock(skuList);
            stomap = HasStocks.stream().collect(Collectors.toMap(t1 -> t1.getSkuId(), t2 -> t2.getHashStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}", e);
        }
        System.out.println("商品库存");
        System.out.println(stomap);
        //2封装每个sku的信息
        List<SkuEsModel.Attrs> finalAttrs = attrs;
        Map<Long, Boolean> finalStomap = stomap;
        List<SkuEsModel> esModelList = skuInfoEntities.stream().map(item -> {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(item, esModel);
            esModel.setSkuPrice(item.getPrice());
            esModel.setSkuImg(item.getSkuDefaultImg());

            /**
             * hasStock=null, hotScore=null, brandName=null, brandImg=null, catalogName=null, attrs=null
             */
            // TODO: 2022/5/11  查询是否有库存
            if (finalStomap != null)
                esModel.setHasStock(finalStomap.get(item.getSkuId()));
            // TODO: 2022/5/11 查询热度评分
            esModel.setHotScore((long) 0);
            // TODO: 2022/5/11 查询品牌的分类和信息
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            System.out.println(item);
            System.out.println("brand属性");
            System.out.println(brandEntity);
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            System.out.println(item.getCatalogId());
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            System.out.println(categoryEntity);
            esModel.setCatalogName(categoryEntity.getName());
            esModel.setAttrs(finalAttrs);
            return esModel;
        }).filter(Objects::nonNull).collect(Collectors.toList());

        System.out.println(esModelList);
        // TODO: 2022/5/11 将数据发给es保存
        R r = elassticFeignService.elasticSava(esModelList);
        System.out.println(r);
        System.out.println(r.getCode());
        if(r.getCode()==200 ||r.getCode()==0){
            //远程调用成功
            // TODO: 2022/5/12 上架成功 将上架状态改为上架
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.PUBLISH_status.ATTR_TYPE_UP.getCode());
        }else {
            // TODO: 2022/5/12 远程接口调用失败 ，重试机制
            System.out.println("调用失败");
        }

        return  r;
    }

}